package xyz.liuz.edb.clienttest;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;

import java.util.Date;
import java.util.List;

/**
 * 使用 FrameDecoder时需要考虑到读到的数据有可能是不完整的，而使用ReplayingDecoder就可以假定读到了全部的数据
 * */
public class ClientDecoder extends ReplayingDecoder<Void> {
	@Override
	protected void decode(ChannelHandlerContext paramChannelHandlerContext,
			ByteBuf paramByteBuf, List<Object> paramList) throws Exception {
		System.out.println("解码器运行啦");
		System.out.println("长度1:"+paramByteBuf.readableBytes());
		int messageType = paramByteBuf.readInt();// 消息类型
		System.out.println("读取到的是:"+messageType);
		int msgLength = paramByteBuf.readInt();// 消息类型
		System.out.println("2读取到的是:"+msgLength);
		System.out.println("长度2:"+paramByteBuf.readableBytes());

//		byte[] msgLenByte = new byte[2];
//		paramByteBuf.readBytes(msgLenByte);
//
//		int msgLength = Integer.parseInt(new String(msgLenByte,
//				CharsetUtil.UTF_8));
		System.out.println("长度L"+msgLength);
		byte[] msgByte = new byte[msgLength];
		paramByteBuf.readBytes(msgByte);
		paramList.add(new String(msgByte, CharsetUtil.UTF_8));


	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		IdleStateEvent event = (IdleStateEvent) evt;
		System.out.println("这里也有超时的吗？"+event.state()+":::"+new Date());
		ctx.channel().close();
	}
}
